package com.bacon.gmall.product.service.impl;

import com.bacon.gmall.product.service.TestLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2020-12-25 16:45
 * @description:
 */
@Service
public class TestLockServiceImpl implements TestLockService {

    private final String LOCK = "Lock";

    @Autowired
    private RedisTemplate redisTemplate;


    public void add() {

        //使用UUID判断锁是否是自己的
        String uuid = UUID.randomUUID().toString();
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(LOCK, uuid, 5, TimeUnit.SECONDS);

        //true：拿到锁
        if (aBoolean) {
            try {
                Integer num = (Integer) redisTemplate.opsForValue().get("num");
                num++;
                redisTemplate.opsForValue().set("num", num);
                redisTemplate.delete(LOCK);
            } finally {

                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(LOCK), uuid);

            }
        } else {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            redisTemplate.opsForValue().get(LOCK);

        }


    }
}
